package com.tengju.user.application.login;

import com.tengju.user.application.shared.ApplicationException;
import com.tengju.user.application.shared.ApplicationExceptionCode;
import com.tengju.user.domain.model.login.LoginForm;
import com.tengju.user.domain.model.login.LoginResult;
import com.tengju.user.domain.model.login.UserAccount;
import com.tengju.user.domain.model.login.UserType;
import com.tengju.user.domain.model.user.*;
import com.tengju.user.domain.shared.DomainException;
import com.tengju.user.domain.shared.DomainExceptionCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

@Slf4j
@Service("pwdLoginService")
public class PwdLoginStrategyImpl implements LoginStrategy {

    private UserAccountRepository userAccountRepository;
    private UserInfoRepository userInfoRepository;
    private UserStaffRepository userStaffRepository;

    @Autowired
    public PwdLoginStrategyImpl(UserAccountRepository userAccountRepository, UserInfoRepository userInfoRepository, UserStaffRepository userStaffRepository) {
        this.userAccountRepository = userAccountRepository;
        this.userInfoRepository = userInfoRepository;
        this.userStaffRepository = userStaffRepository;
    }

    @Override
    public LoginResult login(LoginForm loginForm, UserAccount userAccount) {

        if (userAccount == null) {
            throw DomainException.error(DomainExceptionCode.PWD_ERROR);
        }

        userAccount.checkPwd(loginForm.getPassword());

        LoginDesc loginDesc;
        if (UserType.USER == loginForm.getUserType()) {
            loginDesc = userInfoRepository.getByUserId(userAccount.getUserId());
        } else if (UserType.STAFF == loginForm.getUserType()) {
            loginDesc = userStaffRepository.queryUserStaff(userAccount.getStaffId());
        } else {
            log.error("userType error,mobile:{}",loginForm.getUsername());
            throw ApplicationException.error(ApplicationExceptionCode.LOGIN_FAIL);
        }

        //更新上次登录ip及登录时间
        userAccount.login(loginForm.getLoginIp());
        userAccountRepository.login(userAccount);

        return new LoginResult(loginDesc.getId(),
                userAccount.getUsername(),
                loginDesc.getNickName(),
                loginDesc.getHeadImage(),
                null,
                loginDesc.getUserType(),
                loginDesc.getUserIdCode(),
                new ArrayList<>(),
                new ArrayList<>(),
                userAccount.getPassword(),
                new ArrayList<>(),
                null);
    }

    @Override
    public LoginResult registerAndLogin(LoginForm loginForm) {

        //账号密码登陆不支持自动注册
        log.error("密码登陆不支持自动注册,手机号：{}",loginForm.getUsername());
        throw DomainException.error(DomainExceptionCode.NOT_REGIST_ERROR);

    }
}
